<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>人员工分</span>
          <el-button size="mini" style="float: right" @click="router.go(-1)">返回</el-button>
        </div>
      </template>

      <span style="font-size: 15px"> 年份：</span>
      <el-select v-model="searchForm.year" placeholder="Select" style="width: 140px" @change="searchOrder">
        <el-option v-for="item in years" :key="item.year" :value="item.year" />
      </el-select>

      <span style="font-size: 15px; margin-left: 20px"> 月份：</span>
      <el-select v-model="searchForm.month" placeholder="Select" style="width: 80px" @change="searchOrder">
        <el-option v-for="item in 12" :key="item" :value="item" :label="`${item}月`" />
      </el-select>

      <el-button type="success" style="float:right;margin-right:10px" @click="download">
        导出当月数据<el-icon class="el-icon--right">
          <Download />
        </el-icon>
      </el-button>

      <el-tabs class="el-tab">
        <el-tab-pane label="编辑">
          <el-table :data="tableDataBianji" :span-method="BianjiSpanMethod" border style="width: 100%; margin-top: 20px">
            <el-table-column prop="member" label="人员名称" width="140" align="center" />
            <el-table-column prop="product_name" label="项目名称" width="300" />
            <el-table-column prop="score1" :label="leaders[0]" align="center">
              <template #default="scope">
                <div v-for="score in scope.row.scores" :key="score.scorer">
                  <div v-if="score.scorer === leaders[0]">
                    {{ score.score }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="score2" :label="leaders[1]" align="center">
              <template #default="scope">
                <div v-for="score in scope.row.scores" :key="score.scorer">
                  <div v-if="score.scorer === leaders[1]">
                    {{ score.score }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="score3" :label="leaders[2]" align="center">
              <template #default="scope">
                <div v-for="score in scope.row.scores" :key="score.scorer">
                  <div v-if="score.scorer === leaders[2]">
                    {{ score.score }}
                  </div>
                </div>
              </template></el-table-column>
            <el-table-column prop="score4" :label="leaders[3]" align="center">
              <template #default="scope">
                <div v-for="score in scope.row.scores" :key="score.scorer">
                  <div v-if="score.scorer === leaders[3]">
                    {{ score.score }}
                  </div>
                </div>
              </template></el-table-column>
            <el-table-column prop="average_score" label="平均分" align="center" />
            <el-table-column prop="total_score" label="总分" align="center">
              <template #default="scope">
                {{ getMemberTotalScore(scope.row.member) }}
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="设计">
          <el-table :data="tableDataSheji" :span-method="ShejiSpanMethod" border style="width: 100%; margin-top: 20px">
            <el-table-column prop="member" label="人员名称" width="140" align="center" />
            <el-table-column prop="product_name" label="项目名称" width="300" />
            <el-table-column prop="score1" :label="leaders[0]" align="center">
              <template #default="scope">
                <div v-for="score in scope.row.scores" :key="score.scorer">
                  <div v-if="score.scorer === leaders[0]">
                    {{ score.score }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="score2" :label="leaders[1]" align="center">
              <template #default="scope">
                <div v-for="score in scope.row.scores" :key="score.scorer">
                  <div v-if="score.scorer === leaders[1]">
                    {{ score.score }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="score3" :label="leaders[2]" align="center">
              <template #default="scope">
                <div v-for="score in scope.row.scores" :key="score.scorer">
                  <div v-if="score.scorer === leaders[2]">
                    {{ score.score }}
                  </div>
                </div>
              </template></el-table-column>
            <el-table-column prop="score4" :label="leaders[3]" align="center">
              <template #default="scope">
                <div v-for="score in scope.row.scores" :key="score.scorer">
                  <div v-if="score.scorer === leaders[3]">
                    {{ score.score }}
                  </div>
                </div>
              </template></el-table-column>
            <el-table-column prop="average_score" label="平均分" align="center" />
            <el-table-column prop="total_score" label="总分" align="center">
              <template #default="scope">
                {{ getMemberTotalScore(scope.row.member) }}
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="技术">
          <el-table :data="tableDataJishu" :span-method="JishuSpanMethod" border style="width: 100%; margin-top: 20px">
            <el-table-column prop="member" label="人员名称" width="140" align="center" />
            <el-table-column prop="product_name" label="项目名称" width="300" />
            <el-table-column prop="score1" :label="leaders[0]" align="center">
              <template #default="scope">
                <div v-for="score in scope.row.scores" :key="score.scorer">
                  <div v-if="score.scorer === leaders[0]">
                    {{ score.score }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="score2" :label="leaders[1]" align="center">
              <template #default="scope">
                <div v-for="score in scope.row.scores" :key="score.scorer">
                  <div v-if="score.scorer === leaders[1]">
                    {{ score.score }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="score3" :label="leaders[2]" align="center">
              <template #default="scope">
                <div v-for="score in scope.row.scores" :key="score.scorer">
                  <div v-if="score.scorer === leaders[2]">
                    {{ score.score }}
                  </div>
                </div>
              </template></el-table-column>
            <el-table-column prop="score4" :label="leaders[3]" align="center">
              <template #default="scope">
                <div v-for="score in scope.row.scores" :key="score.scorer">
                  <div v-if="score.scorer === leaders[3]">
                    {{ score.score }}
                  </div>
                </div>
              </template></el-table-column>
            <el-table-column prop="average_score" label="平均分" align="center" />
            <el-table-column prop="total_score" label="总分" align="center">
              <template #default="scope">
                {{ getMemberTotalScore(scope.row.member) }}
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import workApi from '../../api/work'
import * as XLSX from 'xlsx'
import { useRoute,useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
const tableData = ref([])
const tableDataBianji = ref([])
const tableDataSheji = ref([])
const tableDataJishu = ref([])
const years = ref()
const leaders = ref(['黄昕', '徐洁', '陈海伟', '庄小蕾'])
// 搜索条件
const searchForm = reactive({ ...route.query });
// 获取全局变量
const username = sessionStorage.getItem('username')

onMounted(async () => {
  const yearRes = await workApi.getDistinctYears()
  years.value = yearRes.data
  console.log(years.value)
  searchForm.year = route.query.year
  searchForm.month = route.query.month
  searchOrder()
  searchForm.month = route.query.month+"月"
})

// 获取数据列表
const searchOrder = async () => {
  tableData.value = []
  tableDataBianji.value = []
  tableDataSheji.value = []
  tableDataJishu.value = []
  const resData = await workApi.getAllScoresByMonth(searchForm)

  // 创建一个 Map 对象，用于存储相同 id 的数据
  const idMap = new Map()

  // 遍历数据数组，将具有相同 id 的数据的 url 合并到一个数组中
  resData.data.forEach((item) => {
    const id = item.id;
    if (idMap.has(id)) {
      idMap.get(id).scores.push({ score: item.score, scorer: item.scorer, score_remark: item.score_remark });
    } else {
      idMap.set(id, { ...item, scores: [{ score: item.score, scorer: item.scorer, score_remark: item.score_remark }] });
    }
  });

  // 将 Map 对象转换为数组
  const result = Array.from(idMap.values());
  tableData.value = result;

  // 遍历 tableData 中的每个记录
  tableData.value.forEach((item) => {
    // 给每条记录加上一个平均分
    if (item.scores && item.scores.length > 0) {
      const totalScore = item.scores.reduce((sum, scoreObj) => sum + scoreObj.score, 0);
      const averageScore = (totalScore / item.scores.length).toFixed(2);
      item.average_score = parseInt(averageScore);
    } else {
      item.average_score = '0'; // 如果没有 scores，平均分为 0
    }

    if (item.type == "编辑") {
      tableDataBianji.value.push(item);
    }
    if (item.type == "设计") {
      tableDataSheji.value.push(item);
    }
    if (item.type == "技术") {
      tableDataJishu.value.push(item);
    }
  });

  // 排序函数
  const sortByMember = (a, b) => a.member.localeCompare(b.member);

  // 按照 member 排序
  tableDataBianji.value.sort(sortByMember);
  tableDataSheji.value.sort(sortByMember);
  tableDataJishu.value.sort(sortByMember);

  // console.log(JSON.stringify(tableDataSheji.value));
}

const getMemberTotalScore = (member) => {
  const memberRows = tableData.value.filter(row => row.member === member);
  return memberRows.reduce((total, row) => {
    return total + ((row.average_score) || 0);
  }, 0);
};


const BianjiSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  const allRows = tableDataBianji.value;
  const member = row.member;

  // Helper function to calculate rowspan
  const calculateRowSpan = (property) => {
    let span = 1;
    for (let i = rowIndex + 1; i < allRows.length; i++) {
      if (allRows[i][property] !== member) break;
      span++;
    }
    return span;
  };

  // Handle member and total_score columns
  if (column.property === 'member' || column.property === 'total_score') {
    if (rowIndex === 0 || allRows[rowIndex - 1].member !== member) {
      const rowspan = calculateRowSpan('member');
      return {
        rowspan,
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
  return {
    rowspan: 1,
    colspan: 1
  };
};


const ShejiSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  const allRows = tableDataSheji.value;
  const member = row.member;

  // Helper function to calculate rowspan
  const calculateRowSpan = (property) => {
    let span = 1;
    for (let i = rowIndex + 1; i < allRows.length; i++) {
      if (allRows[i][property] !== member) break;
      span++;
    }
    return span;
  };

  // Handle member column
  if (column.property === 'member') {
    if (rowIndex === 0 || allRows[rowIndex - 1].member !== member) {
      const rowspan = calculateRowSpan('member');
      return {
        rowspan,
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }

  // Handle total_score column
  if (column.property === 'total_score') {
    if (rowIndex === 0 || allRows[rowIndex - 1].member !== member) {
      const rowspan = calculateRowSpan('member');
      return {
        rowspan,
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
};

const JishuSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  const allRows = tableDataJishu.value;
  const member = row.member;

  // Helper function to calculate rowspan
  const calculateRowSpan = (property) => {
    let span = 1;
    for (let i = rowIndex + 1; i < allRows.length; i++) {
      if (allRows[i][property] !== member) break;
      span++;
    }
    return span;
  };

  // Handle member column
  if (column.property === 'member') {
    if (rowIndex === 0 || allRows[rowIndex - 1].member !== member) {
      const rowspan = calculateRowSpan('member');
      return {
        rowspan,
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }

  // Handle total_score column
  if (column.property === 'total_score') {
    if (rowIndex === 0 || allRows[rowIndex - 1].member !== member) {
      const rowspan = calculateRowSpan('member');
      return {
        rowspan,
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
};



// 导出数据 begin
const calculateRowSpanForDownload = (tableData, startIndex, property) => {
  let span = 1;
  const allRows = tableData;
  const member = allRows[startIndex][property];
  for (let i = startIndex + 1; i < allRows.length; i++) {
    if (allRows[i][property] !== member) break;
    span++;
  }
  return span;
};

const exportData = (tableData) => {
  return tableData.map(row => {
    const rowData = {
      '人员名称': row.member,
      '项目名称': row.product_name,
      [leaders.value[0]]: row.scores.find(score => score.scorer === leaders.value[0])?.score || '',
      [leaders.value[1]]: row.scores.find(score => score.scorer === leaders.value[1])?.score || '',
      [leaders.value[2]]: row.scores.find(score => score.scorer === leaders.value[2])?.score || '',
      [leaders.value[3]]: row.scores.find(score => score.scorer === leaders.value[3])?.score || '',
      '平均分': row.average_score,
      '总分': getMemberTotalScore(row.member)
    };
    return rowData;
  });
};

const download = () => {
  const exportDataBianji = exportData(tableDataBianji.value)
  const exportDataSheji = exportData(tableDataSheji.value)
  const exportDataJishu = exportData(tableDataJishu.value)

  const wb = XLSX.utils.book_new();
  const wsBianji = XLSX.utils.json_to_sheet(exportDataBianji);
  const wsSheji = XLSX.utils.json_to_sheet(exportDataSheji);
  const wsJishu = XLSX.utils.json_to_sheet(exportDataJishu);

  XLSX.utils.book_append_sheet(wb, wsBianji, '编辑');
  XLSX.utils.book_append_sheet(wb, wsSheji, '设计');
  XLSX.utils.book_append_sheet(wb, wsJishu, '技术');

  const mergesBianji = [];
  const mergesSheji = [];
  const mergesJishu = [];

  // Calculate merges
  tableDataBianji.value.forEach((row, rowIndex) => {
    if (rowIndex === 0 || tableDataBianji.value[rowIndex - 1].member !== row.member) {
      const memberSpan = calculateRowSpanForDownload(tableDataBianji.value, rowIndex, 'member');
      const dataRowIndex = rowIndex + 1;  // Adjust for header row
      mergesBianji.push({ s: { r: dataRowIndex, c: 0 }, e: { r: dataRowIndex + memberSpan - 1, c: 0 } });
      mergesBianji.push({ s: { r: dataRowIndex, c: Object.keys(exportDataBianji[0]).length - 1 }, e: { r: dataRowIndex + memberSpan - 1, c: Object.keys(exportDataBianji[0]).length - 1 } });
    }
  });
  tableDataSheji.value.forEach((row, rowIndex) => {
    if (rowIndex === 0 || tableDataSheji.value[rowIndex - 1].member !== row.member) {
      const memberSpan = calculateRowSpanForDownload(tableDataSheji.value, rowIndex, 'member');
      const dataRowIndex = rowIndex + 1;  // Adjust for header row
      mergesSheji.push({ s: { r: dataRowIndex, c: 0 }, e: { r: dataRowIndex + memberSpan - 1, c: 0 } });
      mergesSheji.push({ s: { r: dataRowIndex, c: Object.keys(exportDataSheji[0]).length - 1 }, e: { r: dataRowIndex + memberSpan - 1, c: Object.keys(exportDataSheji[0]).length - 1 } });
    }
  });
  tableDataJishu.value.forEach((row, rowIndex) => {
    if (rowIndex === 0 || tableDataJishu.value[rowIndex - 1].member !== row.member) {
      const memberSpan = calculateRowSpanForDownload(tableDataJishu.value, rowIndex, 'member');
      const dataRowIndex = rowIndex + 1;  // Adjust for header row
      mergesJishu.push({ s: { r: dataRowIndex, c: 0 }, e: { r: dataRowIndex + memberSpan - 1, c: 0 } });
      mergesJishu.push({ s: { r: dataRowIndex, c: Object.keys(exportDataJishu[0]).length - 1 }, e: { r: dataRowIndex + memberSpan - 1, c: Object.keys(exportDataJishu[0]).length - 1 } });
    }
  });

  wsBianji['!merges'] = mergesBianji;
  wsSheji['!merges'] = mergesSheji;
  wsJishu['!merges'] = mergesJishu;

  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
  const blob = new Blob([wbout], { type: 'application/octet-stream' });
  const fileName = searchForm.year + "年" + searchForm.month + "月" + '人员工分表.xlsx';

  if (typeof window.navigator.msSaveBlob !== 'undefined') {
    window.navigator.msSaveBlob(blob, fileName);
  } else {
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    setTimeout(() => {
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    }, 0);
  }
}
// 导出数据 end


</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  width: 100%;
  height: 100%;
}

.el-tag {
  margin: 5px 5px 5px 0;
}

.el-tab {
  margin: 20px 10px;
}
</style>
